import React, {Component} from 'react'


import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import PerformancePage from "./PerformancePage";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import MatrixSubBCPage from "./MatrixSubBCPage";
import RegisterIBMThreePage from "../../common/register/RegisterIBMThreePage";
import SubAccountsPage from "./SubAccountsPage";
import AlertDialog from "../../../custom/AlertDialog";


const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});

export default class U_2ProgramPage extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.country = '';
        this.planNamesData = [
            {name: I18n.t('b.ActivatedBusiness'), color: 'black', value: null, valueText: 0},
            {name: I18n.t('b.noQualifiedBusinessCenters'), color: '#D2D2D2', value: [], valueText: 0},
            {name: I18n.t('b.qualifiedBusinessCenters'), color: '#A0A0A0', value: [], valueText: 0},
            {name: I18n.t('b.completedCycles'), color: '#A0A0A0', value: [], valueText: 0},
            // {name: I18n.t('default.newRegistrants'), color: '#b1b1b1', value: null, valueText: 0},
        ];


        this.menuData = [
            I18n.t('b.businessCenter'),
            I18n.t('default.identity'),
            I18n.t('b.activationDate')
        ];

        this.state = {
            isLoading: false,
            alertVisible: false,
            plansData: [],
            usersData: [],
            userData: props.userData,
            planPerformanceValue: 3123,
        }

    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this.country = null;
        this.planNamesData = null;
    }

    componentDidMount() {
        this.setUsersInfo(this.props.U_2ProgramData)
    }


    /**
     * 获取摸个用户的子账号
     */
    onLoadData() {
        this.setState({
            isLoading: true
        });
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + this.state.userData.main_user_id + '&rank=' + this.props.rank)
            .then((result) => {
                if (result.code === 200) {
                    this.setUsersInfo(result.data)
                } else {
                    this.setState({
                        isLoading: false
                    });
                }

            })
            .catch((error) => {
                this.setState({
                    isLoading: false
                });

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('MatrixPlanPage-----onLoadData--error: ', error);
            })
    }


    /**
     * setUsersInfo
     *@param data
     */
    setUsersInfo(data) {
        let length = data.length;
        this.planNamesData[1].value = [];
        this.planNamesData[2].value = [];
        this.planNamesData[3].value = [];
        for (let i = 0; i < length; i++) {
            let datum = data[i];
            if (datum.is_ibm === 1) {
                this.planNamesData[1].value.push(datum);
            } else {
                this.planNamesData[2].value.push(datum);
            }

            if (datum.level === this.props.rank) {
                this.planNamesData[3].value.push(datum);
            }

            console.log(datum.level)

        }

        this.planNamesData[0].valueText = length;
        this.planNamesData[1].valueText = this.planNamesData[1].value.length;
        this.planNamesData[2].valueText = this.planNamesData[2].value.length;
        this.planNamesData[3].valueText = this.planNamesData[3].value.length;


        this.setState({
            isLoading: false,
            usersData: data,
        })
    }

    /**
     *
     */
    planOnClick(item, index) {
        this.props.navigator.push({
            component: SubAccountsPage,
            name: 'SubAccountsPage',
            params: {
                users: (item ? item.value : null) || this.state.usersData,
                title: item.name,
            }
        })
    }

    /**
     * 实现PlanLable
     * */
    renderPlanLable(rowData, index) {

        return (<TouchableOpacity
            key={index}
            onPress={() => this.planOnClick(rowData, index)}
            style={[StyleUtils.justifySpace, {marginBottom: 22}]}>
            <View style={{width: 22, height: 22, backgroundColor: rowData.color}}/>
            <Text style={[styles.planLable, StyleUtils.smallFont]}>{rowData.name}</Text>
            <Text style={[{fontSize: 16, color: 'black'}, StyleUtils.smallFont]}>{rowData.valueText}</Text>
        </TouchableOpacity>)
    }

    /**
     * 实现menuTitle
     * */
    renderMenuTitle() {
        return (<View style={[StyleUtils.center, styles.menuTitle]}>
            <Text
                numberOfLines={2}
                style={{
                    color: 'white',
                    fontSize: 10,
                    textAlign: 'center',
                    paddingLeft: 4,
                    paddingRight: 4
                }}>{I18n.t('b.businessCenter')}</Text>
        </View>)
    }

    /**
     * 实现menuItem
     * */
    // renderMenuViews() {
    //     return <View style={{width: 80, flex: 1, backgroundColor: 'black'}}>
    //
    //         <Text style={{color: 'white'}}>asfs</Text>
    //
    //     </View>
    // }

    /**
     * 实现menu
     * */
    renderMenuViews(rowData, index) {
        return <TouchableOpacity
            onPress={() => {
                this.props.navigator.push({
                    component: MatrixSubBCPage,
                    name: 'MatrixSubBCPage',
                    params: {
                        usersData: this.state.usersData,
                        titleText: this.props.title,
                        selectDataIndex: index,
                    }
                })
            }}
            style={[StyleUtils.justifySpace]}>

            {this.menuData.map((item, i) => {

                let text = 0;
                switch (i) {
                    case 0:
                        text = rowData.rand_id;
                        break;
                    case 1:
                        text = rowData.user_level ? rowData.user_level.level_name : '';
                        // text = rowData.is_buy === 0 ? I18n.t('default.no') : I18n.t('default.activated');
                        break;
                    case 2:
                        text = rowData.active_time && rowData.active_time.substring(0, 11);
                        break;
                }

                return <View style={[StyleUtils.center, styles.menuTitle, {
                    height: 32,
                    backgroundColor: index % 2 === 0 ? "white" : '#f0f0f0'
                }]}>
                    <Text
                        numberOfLines={2}
                        style={[{
                            color: 'black',
                            fontSize: 10,
                            textAlign: 'center',
                            paddingLeft: 4,
                            paddingRight: 4
                        }, StyleUtils.smallFont]}>{text}</Text>
                </View>

            })}

        </TouchableOpacity>
    }


    startBusiness(userData) {
        if (userData.is_open_account6 > 0) {
            this.props.navigator.push({

                component: RegisterIBMThreePage,
                name: 'RegisterIBMThreePage',
                params: {
                    selectPlan: {rank: this.props.rank, rank_name: this.props.title,}
                }

            })
        } else {
            this.setState({
                alertVisible: true,
            })
        }
    }


    /**
     * 实现menuTitle
     * */
    renderMenuTitle() {
        return (<View style={StyleUtils.justifySpace}>

                {this.menuData.map((item, i) => {
                    return <View style={[StyleUtils.center, styles.menuTitle]}>
                        <Text
                            numberOfLines={2}
                            style={{
                                color: 'white',
                                fontSize: 10,
                                textAlign: 'center',
                                paddingLeft: 4,
                                paddingRight: 4
                            }}>{item}</Text>
                    </View>

                })}

            </View>
        )
    }


    render() {


        let props = this.props;
        //奖金
        let _bonus = 0;
        if (props.rewardStatisticsData) {
            _bonus = props.rewardStatisticsData.rank[this.props.rank].pv
        }

        let userData = this.state.userData;
        let contentView = (userData && userData.open_plan && (userData.open_plan + '').indexOf(this.props.rank) !== -1 ?
                <View>
                    <View style={{padding: 20}}>
                        {/*<TouchableOpacity*/}
                        {/*style={[StyleUtils.justifySpace, {backgroundColor: 'black', padding: 16}]}>*/}

                        {/*<Text style={{color: 'white'}}>{I18n.t('b.myLevel')}</Text>*/}

                        {/*<View style={[StyleUtils.rowDirection, StyleUtils.center]}>*/}
                        {/*<Text style={{color: 'white', paddingRight: 8}}>{I18n.t('default.businessInfor')}</Text>*/}
                        {/*<Image*/}
                        {/*style={{width: 12, height: 12, tintColor: 'white'}}*/}
                        {/*source={require('../../../res/images/ic_right_more.png')}/>*/}
                        {/*</View>*/}

                        {/*</TouchableOpacity>*/}


                        {/*<Text style={{*/}
                        {/*fontSize: 18,*/}
                        {/*color: 'black',*/}
                        {/*marginTop: 36,*/}
                        {/*marginBottom: 36,*/}
                        {/*width: '100%'*/}
                        {/*}}>{I18n.t('b.estimatedPV')}</Text>*/}


                        <View style={{alignItems: 'center', paddingTop: 24, paddingBottom: 24}}>
                            <Text style={{textAlign: 'center'}}>{I18n.t('b.ActivatedBusiness')}</Text>

                            <View style={[StyleUtils.justifySpace, {marginTop: 26, marginBottom: 26}]}>
                                <Image
                                    resizeMode="cover"
                                    style={{width: 48, height: 48, resizeMode: 'cover'}}
                                    source={require('../../../res/images/ic_shop.png')}/>
                                <Text
                                    style={{fontSize: 38, alignItems: 'center'}}>+ {this.state.usersData.length}</Text>

                            </View>
                        </View>

                        {this.planNamesData.map((item, i) => {
                            return this.renderPlanLable(item, i);
                        })}
                        {ViewUtils.getButton('My performance', null, [styles.topBtnStyle, {marginTop: 36,}], {color: 'black'})}

                        <Text style={{
                            fontSize: 18,
                            color: 'black',
                            marginTop: 26,
                            textAlign: 'center',
                            width: '100%'
                        }}>{I18n.t('b.estimatedPV')}</Text>
                        <PerformancePage
                            value={_bonus}
                            type={0}
                        />
                    </View>
                    {/*<ScrollView*/}
                    {/*horizontal={true}>*/}
                    {/*<View>*/}
                    {this.renderMenuTitle()}
                    <ListView
                        renderRow={(rowData, sectionID, rowID) => this.renderMenuViews(rowData, rowID)}
                        dataSource={ds.cloneWithRows(this.state.usersData)}
                    />
                    {/*</View>*/}

                    {/*</ScrollView>*/}


                    <View style={{padding: 16}}>
                        {ViewUtils.getButton(I18n.t('b.activateBusiness'), () => {
                            this.startBusiness(userData)
                        }, {marginTop: 48, height: 42})}
                    </View>

                </View> :
                <View style={StyleUtils.center}>
                    <Text style={{textAlign: 'center'}}>
                        {I18n.t('b.subscribeNow')}
                    </Text>
                    {ViewUtils.getButton('Subscribe', () => {
                        this.startBusiness(userData)
                    }, [styles.topBtnStyle, {marginTop: 38}], {color: 'black'})}
                </View>
        );

        return (<View style={StyleUtils.flex}>

            <Navigation
                titleImage={require('../../../res/images/ic_ipar_logo.png')}
                onClickLeftBtn={() => props.navigator.pop()}/>
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onLoadData()}
                    />
                }
            >
                <View>

                    {ViewUtils.getTitleView(props.title, I18n.t('b.allAboutProgram'))}

                    {/*{ViewUtils.getButton('Check details', null, styles.topBtnStyle, {color: 'black'})}*/}

                    {contentView}


                </View>

            </ScrollView>


            <AlertDialog
                contentTv={I18n.t('b.oppsStartNewBusiness')}
                singleBtnOnclick={() => {
                    this.setState({
                        alertVisible: false
                    })
                }}
                visible={this.state.alertVisible}
                requestClose={() => {
                    this.setState({
                        alertVisible: false
                    })
                }}/>

        </View>)
    }


}

const styles = StyleSheet.create({

    topBtnStyle: {
        backgroundColor: 'white',
        borderWidth: 1,
        height: 42,
        borderColor: '#e7e7e7',
        marginBottom: 28,
    },

    planLable: {
        borderColor: 'black',
        flex: 1,
        paddingLeft: 8,
        textAlign: 'left'
    },
    reentryViewStyle: {
        borderTopWidth: 1,
        borderBottomWidth: 1,
        borderColor: '#e7e7e7',
        marginTop: 32,
        paddingTop: 16,
        paddingBottom: 16,

    },

    circularText: {
        color: 'white',
        textAlign: 'center',
    },

    menuTitle: {
        width: 88,
        height: 42,
        flex: 1,
        backgroundColor: 'black'
    },

    titleText: {
        marginTop: 16,
        fontSize: 18,
        color: 'black',
    },
});